package fr.vod.threads;

import java.net.DatagramPacket;
import java.util.LinkedList;
import java.util.Queue;
import fr.vod.gauss.File.File;
import fr.vod.gauss.matrice.Equation;
import fr.vod.gauss.net.Format;
import fr.vod.gauss.net.FormatImpl;
import fr.vod.net.Receiver;

/**
 * 
 * @author drazanakoto
 * 
 */
public class DataReceiver extends Thread {

	private Receiver receiver;
	private boolean end;
	private int blockSize;
	private int packetSize;
	private long blockNumber;
	private Queue<Equation> buffer;
	private long receiveBlock = 0;

	/**
	 * 
	 * @param receiver
	 * @param blockSize
	 * @param packetSize
	 */
	public DataReceiver(Receiver receiver, int blockSize, int packetSize) {
		this.receiver = receiver;
		this.blockSize = blockSize;
		this.packetSize = packetSize;
		buffer = new LinkedList<Equation>();
	}

	/**
	 * 
	 * @param blockNumber
	 */
	public void setBlockNumber(long blockNumber) {
		this.blockNumber = blockNumber;
		buffer.clear();
	}

	public void run() {
		Format f = new FormatImpl();
		DatagramPacket dp;
		byte[] tmp;
		byte[] data = new byte[1 + File.SIZE_OF_BLOCK_NUMBER + 2 * packetSize
				+ 1];
		while (!end) {
			try {
				dp = receiver.receivePacket();

				tmp = dp.getData();

				/** **/
				System.arraycopy(tmp, 0, data, 0, data.length);
				if (f.respectFormat(data, packetSize)
						&& (receiveBlock = f.getBlockNumber(data)) == blockNumber) {
					if (f.isXor(data)) {
						buffer.add(f.format(data, blockSize, packetSize));
					} else {
						buffer.addAll(f.formatAllNotXor(data, blockSize,
								packetSize));
					}
				}
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 
	 */
	public void end() {
		end = true;
	}

	/**
	 * 
	 * @return
	 */
	public Equation getData() {
		return buffer.poll();
	}

	/**
	 * 
	 * @return
	 */
	public long getReceiveBlock() {
		return receiveBlock;
	}
}
